package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.enums.OrderTypeEnum;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class OpenSchoolServiceImpl implements IOpenSchoolService {

    @Autowired
            @Lazy
    IOrderDetailService iOrderDetailService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    IOrderApplyService iOrderApplyService;

    @Autowired
    @Lazy
    ICoursePricingService iCoursePricingService;

    @Autowired
    @Lazy
    IdWorker idWorker;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    IOrderCoursePricingService iOrderCoursePricingService;

    @Autowired
    @Lazy
    IRenewDataService iRenewDataService;

    @Autowired
    @Lazy
    IStudentTypeService iStudentTypeService;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    IOrderTransferService iOrderTransferService;

    @Autowired
    @Lazy
    IOrderTransferDetailService iOrderTransferDetailService;

    @Autowired
    @Lazy
    IStaffService iStaffService;

    /**
     * 课程顺延
     * @param yearAndQuarter 被顺延的年份与学期（例：20234）
     * @param plusClassNum 年级是否要增加，1为增加一个年级（例：1）
     * @param nextQuarterNum 顺延到下个学期的id(例：4)
     */
    @Async("onlineAsync")
    @Override
    public void courseAuto(Integer yearAndQuarter, Integer plusClassNum, Integer nextQuarterNum,Long studentId) {
        Integer oldVersion = 0;
        Integer afterVersion = 1;//新学期的数据版本为0开始，被顺延后改为1

        Integer lessonType = 1;//精品课

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("year_and_quarter", yearAndQuarter);
        orderDetailQueryWrapper.gt("residue_course_count", 0);
        orderDetailQueryWrapper.eq("version", oldVersion);
        orderDetailQueryWrapper.ne("status", 2);
        orderDetailQueryWrapper.eq("lesson_type", lessonType);
        orderDetailQueryWrapper.eq(studentId != null,"student_id", studentId);
        //orderDetailQueryWrapper.last("limit 10");
        Long count = iOrderDetailService.count(orderDetailQueryWrapper);

        //log.info("count:" + count);

        List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);
        Integer j = 0;
        for (OrderDetail orderDetailOld : orderDetailList) {
            try {
                Course courseOld = iCourseService.getById(orderDetailOld.getCourseId());
                OrderApply orderApplyOld = iOrderApplyService.getById(orderDetailOld.getOrderId());

                Integer yearClassId = courseOld.getYearClassId().getKey() + plusClassNum;//年级加1

                QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
                courseQueryWrapper.eq("subjects_id", courseOld.getSubjectsId());
                //courseQueryWrapper.eq("year_class_id",courseOld.getYearClassId().getKey()+1);//年级加1
                courseQueryWrapper.eq("year_class_id", yearClassId);
                courseQueryWrapper.eq("quarter_num", nextQuarterNum);//顺延到暑假班
                courseQueryWrapper.eq("lesson_type", orderDetailOld.getLessonType());
                courseQueryWrapper.eq("status", 1);//状态为开启的
                courseQueryWrapper.and(i -> i.eq("opening_school_type", 1).or().inSql("id", "select for_id from appoint_school where type = 1 and school_id= " + orderDetailOld.getSchoolId() + " "));

                courseQueryWrapper.last("limit 1");

                Course course = iCourseService.getOne(courseQueryWrapper);
                if (course == null) {
                    System.out.println("课程为空");
                    continue;
                }

                //添加当前报读的续班信息
                Integer yearPart = iQuarterService.getQuarterYearPartForNum(course.getQuarterNum());//获取报读的年份

                QueryWrapper<CoursePricing> coursePricingQueryWrapper = new QueryWrapper<>();

                if (course.getOpeningSchoolType().getKey().equals(1)) {
                    //select id from course_price_school where course_id = and school_id =
                    coursePricingQueryWrapper.inSql("price_school_id", "select id from course_price_school where course_id = " + course.getId() + " and school_id =0 and deleted=0");
                } else {
                    coursePricingQueryWrapper.inSql("price_school_id", "select id from course_price_school where course_id = " + course.getId() + " and school_id =" + orderDetailOld.getSchoolId() + " and deleted=0");

                }

                if ((orderDetailOld.getResidueCourseCount() % 45) == 0) {
                    coursePricingQueryWrapper.eq("count", 45);
                } else {
                    coursePricingQueryWrapper.eq("count", 3);
                }
                //coursePricingQueryWrapper.eq("status",1);
                coursePricingQueryWrapper.last("limit 1");


                CoursePricing coursePricing = iCoursePricingService.getOne(coursePricingQueryWrapper);

                if (coursePricing == null) {
                    System.out.println("没有找到课程价格数据");
                    continue;
                }

                LocalDate nowDate = LocalDate.now();

                //新数据
                OrderApply orderApply = new OrderApply();
                Long orderId = idWorker.nextId();
                orderApply.setId(orderId);
                orderApply.setVersion(1);
                Integer randReceiptNo = CommonUtil.getReceiptNo();
                orderApply.setReceiptNo(randReceiptNo.toString());

                BigDecimal unitPrice = coursePricing.getUnitPrice();

                BigDecimal residuePrice = orderDetailOld.getResiduePrice();//收入为剩余金额
                //应收
                //BigDecimal price = new BigDecimal(orderDetailOld.getResidueCourseCount()).divide(new BigDecimal(3), BigDecimal.ROUND_UP).multiply(unitPrice);

                BigDecimal price = residuePrice;//为收入为剩余金额

                BigDecimal solidPrice = new BigDecimal(0);
                solidPrice = residuePrice;//为收入为剩余金额

                //BigDecimal disPrice = price.subtract(residuePrice);
                BigDecimal disPrice = new BigDecimal(0);

                orderApply.setPrice(price);//应收为剩余费用
                orderApply.setSolidPrice(solidPrice);
                if (disPrice.compareTo(BigDecimal.ZERO) > 0) {
                    orderApply.setDiscountsDate(nowDate);
                }
                orderApply.setDisPrice(disPrice);
                orderApply.setTransferPrice(new BigDecimal(0));//转课抵扣金额,取消使用residuePrice
                orderApply.setStudentId(orderDetailOld.getStudentId());
                orderApply.setSchoolId(orderApplyOld.getSchoolId());
                orderApply.setHandleSchoolId(orderApplyOld.getHandleSchoolId());
                orderApply.setHandleSchoolName(orderApplyOld.getHandleSchoolName());
                orderApply.setHandleDate(nowDate);
                orderApply.setHandlePersonId(orderApplyOld.getHandlePersonId());
                orderApply.setHandlePersonName(orderApplyOld.getHandlePersonName());
                orderApply.setCreatedId(orderApplyOld.getCreatedId());
                orderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_TRANSFER);
                orderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_TRANSFER);
                orderApply.setYearPart(yearPart);//年份
                orderApply.setQuarterNum(course.getQuarterNum());//学期
                orderApply.setLessonType(orderDetailOld.getLessonType());
                orderApply.setYearClassId(yearClassId);
                orderApply.setSubjectsIdStr(courseOld.getSubjectsId().toString());


                String tradeContent = "";//交易内容，交易详情,如：八年级英语【夏季班】，2500元(30课时)*1=2500元，学费优惠100元
                Course outCourse = iCourseService.getById(orderDetailOld.getCourseId());
                tradeContent += "转出：" + outCourse.getName() + "," + orderDetailOld.getResidueCourseCount() + "课时," + orderDetailOld.getResiduePrice() + "元";


                tradeContent += "</br>转入：";

                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setId(idWorker.nextId());
                orderDetail.setOrderId(orderApply.getId());
                orderDetail.setSchoolId(orderDetailOld.getSchoolId());//所属校区
                orderDetail.setStudentId(orderDetailOld.getStudentId());
                orderDetail.setCourseId(course.getId());
                orderDetail.setCourseName(course.getName());
                orderDetail.setSubjectsId(course.getSubjectsId());
                orderDetail.setCoursePriceId(coursePricing.getId());

                orderDetail.setCount(orderDetailOld.getResidueCourseCount() / coursePricing.getCount());//单位数量
                orderDetail.setAllCourseCount(orderDetailOld.getResidueCourseCount());//总课时
                orderDetail.setUseCourseCount(0);
                orderDetail.setResidueCourseCount(orderDetailOld.getResidueCourseCount());//剩余课时
                orderDetail.setCourseHouse(orderDetailOld.getCourseHouse());

                orderDetail.setPrice(residuePrice);//收入为剩余金额
                orderDetail.setSolidPrice(orderDetail.getPrice());
                orderDetail.setResiduePrice(orderDetail.getSolidPrice().subtract(disPrice));
                orderDetail.setDiscountsPrice(disPrice);
                orderDetail.setDiscountsDate(nowDate);
                orderDetail.setServePrice(coursePricing.getServePrice());
                orderDetail.setMaterialsPrice(new BigDecimal(0));
                orderDetail.setEnrollType(1);
                orderDetail.setYearClassId(course.getYearClassId().getKey());

                orderDetail.setHandleDate(orderApply.getHandleDate());
                orderDetail.setOrderType(orderApply.getOrderType());
                orderDetail.setLessonType(orderDetailOld.getLessonType());

                orderDetail.setYearPart(yearPart);
                //设置报读的季度
                orderDetail.setQuarterNum(course.getQuarterNum());
                //年份与季度
                orderDetail.setYearAndQuarter(Integer.parseInt(yearPart + "" + course.getQuarterNum()));
                tradeContent += course.getName() + ",";

                tradeContent += orderDetail.getPrice();

                if (orderDetail.getCoursePriceId() != null) {
                    if (coursePricing != null) {
                        tradeContent += "(" + coursePricing.getCountUnit() + ")*" + orderDetail.getCount() + "=" + orderDetail.getPrice() + "元";
                        orderDetail.setCoursePriceName(coursePricing.getCount() + coursePricing.getCountUnit() + "=" + coursePricing.getAllPrice() + "元");

                        //保存到订单支付价格表
                        OrderCoursePricing orderCoursePricing = new OrderCoursePricing();

                        orderCoursePricing.setId(orderDetail.getId());
                        orderCoursePricing.setPrice(coursePricing.getPrice());
                        orderCoursePricing.setCount(coursePricing.getCount());
                        orderCoursePricing.setCountUnit(coursePricing.getCountUnit());
                        orderCoursePricing.setUnitPrice(coursePricing.getUnitPrice());
                        orderCoursePricing.setChargeMode(coursePricing.getChargeMode());
                        orderCoursePricing.setServePrice(coursePricing.getServePrice());
                        orderCoursePricing.setMaterialsPrice(coursePricing.getMaterialsPrice());
                        orderCoursePricing.setAllPrice(coursePricing.getAllPrice());
                        iOrderCoursePricingService.saveOrUpdate(orderCoursePricing);
                    }
                }


                //iOrderDetailService.save(orderDetail);

                //设置为新生或者老生
                iStudentTypeService.addData(orderDetail.getSchoolId(), orderDetail.getStudentId(), course.getSubjectsId(), 1);

                //更新续班信息是否成功
                //转课
                Grade grade = null;
                iRenewDataService.updateData(orderDetail.getSchoolId(), orderDetail.getStudentId(), course, grade, orderDetail.getAllCourseCount(), 2, orderDetail.getId());

                iRenewDataService.addData(orderDetail.getSchoolId(), orderDetail.getStudentId(), yearPart, course, grade);

                orderApply.setTradeContent(tradeContent);


                //orderDetailOld.setReadingStatus(ReadingStatusEnum.TURN);
                orderDetailOld.setAutoOutHouse(orderDetailOld.getResidueCourseCount());
                orderDetailOld.setResidueCourseCount(0);
                orderDetailOld.setResiduePrice(new BigDecimal(0));

                orderDetailOld.setRollOutHouse(orderDetail.getResidueCourseCount() + orderDetailOld.getRollOutHouse());
                orderDetailOld.setRollOutPrice(orderDetail.getResiduePrice().add(orderDetailOld.getRollOutPrice()));

                orderDetailOld.setVersion(afterVersion);//被顺延的数据
                iOrderDetailService.updateById(orderDetailOld);
                orderDetail.setVersion(0);//新学期的数据版本为0开始
                iOrderDetailService.save(orderDetail);


                Long transferCourseId = null;
                //Boolean isAll = true;//是否全部转出
                OrderTransfer orderTransfer = new OrderTransfer();
                orderTransfer.setOrderId(orderDetail.getSchoolId());
                orderTransfer.setOutSchoolId(orderDetail.getSchoolId());
                orderTransfer.setOutGradeId(orderDetailOld.getCourseId());
                orderTransfer.setInSchoolId(orderDetail.getCourseId());
                orderTransfer.setOutHouse(orderDetail.getResidueCourseCount());
                orderTransfer.setOutPrice(orderDetail.getResiduePrice());
                orderTransfer.setOutType(1);
                orderTransfer.setOrderType(3);
                orderTransfer.setVersion(afterVersion);
                iOrderTransferService.save(orderTransfer);

                OrderTransferDetail orderTransferDetail = new OrderTransferDetail();
                orderTransferDetail.setId(orderTransfer.getId());
                orderTransferDetail.setOrderType(orderApply.getOrderType());
                orderTransferDetail.setOrderId(orderApply.getId());//设置对应的新订单id
                orderTransferDetail.setOldOrderId(orderApplyOld.getId());
                orderTransferDetail.setOldOrderDetailId(orderDetailOld.getId());
                orderTransferDetail.setOutHouse(orderDetail.getResidueCourseCount());
                orderTransferDetail.setOutPrice(orderDetail.getResiduePrice());


                //转课，扣除原有课时
                if (orderDetailOld != null) {
                    //全部转出，把课程设置为转出状态
                    StudentGrade studentGrade = iStudentGradeService.getById(orderDetailOld.getId());
                    if (studentGrade != null) {
                        if (studentGrade.getUseCourseCount() == 0) {
                            //iStudentSchoolService.removeById(studentGrade);
                        } else {
                            //把所在班级设置为结课状态
                            UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
                            //studentGradeUpdateWrapper.set("status",2);
                            studentGradeUpdateWrapper.set("reading_status", ReadingStatusEnum.FINISH.getKey());
                            studentGradeUpdateWrapper.eq("order_detail_id", orderDetailOld.getId());
                            //iStudentGradeService.update(null,studentGradeUpdateWrapper);
                        }
                    }
                }
                orderTransferDetail.setVersion(afterVersion);
                iOrderTransferDetailService.save(orderTransferDetail);
                iOrderApplyService.save(orderApply);

                //结课
                j++;
                System.out.println(orderDetailList.size() + "count:" + count);
                System.out.println("i:" + j);
            } catch (Exception e) {
                System.out.println("报错：");
                System.out.println(e.getMessage());
            }
            //courseQueryWrapper.eq()
            //Course course =
        }
    }

    /**
     *
     * @param outSchoolId 转出校区
     * @param inSchoolId 转入校区
     */
    @Override
    @Async("onlineAsync")
    public void batchChangeSchool(Long outSchoolId, Long inSchoolId, String subjectsIdStr, String yearClassIdStr, Long adminId) throws ParseException {
        //当前季度
        Quarter quarterNow = iQuarterService.getNowQuarter();
        Integer lessonType =1;

        //Long outSchoolId = 1600459509902123009L;//转出校区
        //Long inSchoolId = 1677155560973004802L;//转入校区
        List<Long> subjectsList = new ArrayList<>();
        if (StringUtils.isNotBlank(subjectsIdStr)) {
            List<String> list = Arrays.asList(subjectsIdStr.split(","));
            for (String s : list) {
                subjectsList.add(Long.parseLong(s));
            }
        }else {
            subjectsList.add(1L);
            subjectsList.add(2L);
            subjectsList.add(3L);
        }


        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("school_id", outSchoolId);
        orderDetailQueryWrapper.eq("year_part", quarterNow.getYearPart());
        orderDetailQueryWrapper.eq("quarter_num", quarterNow.getNum());
        orderDetailQueryWrapper.eq("lesson_type", lessonType);
        orderDetailQueryWrapper.inSql(StringUtils.isNotBlank(yearClassIdStr),"year_class_id", yearClassIdStr);
        //orderDetailQueryWrapper.gt("residue_price",0);
        orderDetailQueryWrapper.gt("residue_course_count", 0);
        orderDetailQueryWrapper.ne("status", 2);
        orderDetailQueryWrapper.eq("deleted", 0);
        orderDetailQueryWrapper.groupBy("student_id");
        List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);

        //System.out.println("orderDetailListCount:"+orderDetailList.size());
        List<Long> studentIdList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            studentIdList.add(orderDetail.getStudentId());
        }

        OrderApply orderApply = new OrderApply();
        orderApply.setOutSchoolId(outSchoolId);
        orderApply.setSchoolId(inSchoolId);
        orderApply.setStudentList(studentIdList);
        orderApply.setSubjectsList(subjectsList);
        orderApply.setHandlePersonId(adminId);
        orderApply.setHandlePersonId(adminId);
        Staff staff = iStaffService.getById(adminId);
        if (staff != null){
            orderApply.setHandlePersonName(staff.getName());
        }else {
            orderApply.setHandlePersonName("超级管理员");
        }
        Result result = iOrderApplyService.batchTransferSchoolSave(orderApply);
        //log.error("result:"+result.getMessage());
    }

    @Override
    @Async("onlineAsync")
    public void studentGradeAddOrderId(Integer yearPart,Integer quarterNum,Integer lessonType) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.isNull("order_detail_id");
        studentGradeQueryWrapper.eq("year_part", yearPart);
        studentGradeQueryWrapper.eq("quarter_num", quarterNum);
        studentGradeQueryWrapper.eq("reading_status", 0);
        studentGradeQueryWrapper.eq("lesson_type", lessonType);
        List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
        Integer i = 0;
        Integer j = 0;
        for (StudentGrade studentGrade : studentGradeList) {
            QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
            orderDetailQueryWrapper.eq("school_id", studentGrade.getSchoolId());
            orderDetailQueryWrapper.eq("year_part", yearPart);
            orderDetailQueryWrapper.eq("quarter_num", quarterNum);
            orderDetailQueryWrapper.eq("subjects_id", studentGrade.getSubjectsId());
            orderDetailQueryWrapper.eq("student_id", studentGrade.getStudentId());
            orderDetailQueryWrapper.eq("lesson_type", lessonType);
            orderDetailQueryWrapper.ne("status", 2);
            orderDetailQueryWrapper.orderByDesc("created_at");
            orderDetailQueryWrapper.last("limit 1");
            OrderDetail orderDetail = iOrderDetailService.getOne(orderDetailQueryWrapper);
            if (orderDetail != null) {
                studentGrade.setOrderDetailId(orderDetail.getId());
                studentGrade.setReadingStatus(ReadingStatusEnum.IN_READING);//由预分班改为在读
                //iOrderDetailService.updateById(orderDetail);
                iStudentGradeService.updateById(studentGrade);
                j++;
            }
            i++;
            //log.info(studentGradeList.size() + "---" + i);
        }
        //log.info("j:" + j);
    }

}
